//
//  UserLogTrackService.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/5/18.
//  Copyright © 2023 zwb. All rights reserved.
//
import Foundation
import MessageUI
import UIKit
import skpsmtpmessage
class SKPSMTPMeService: NSObject,SKPSMTPMessageDelegate,refreshable {
    static let shared = SKPSMTPMeService()
     private override init() {}
    
    // 跳转上报页面
    func prepareUpload(vc:UIViewController) {
         
        let bugvc = BugUploadVC()
        vc.navigationController?.pushViewController(bugvc, animated: true)
        
 
    }
    // 个性化处理个人信息字典数据
    var userDic:[String:Any] = ["":""]
 
    
    @objc func startUploadLog(contact:String,remark:String,imgs:[UIImage])  {
        
        var dic = USERINFO.dictionaryRepresentation()
        dic["lMenu"] = nil
        dic["dailiList"] = nil
        dic["managred_unit_nm"] = nil
        dic["managred_unit"] = nil
        dic["vindicator"] = nil
        dic["vindicator_nm"] = nil


         SKPSMTPMeService.shared.userDic = dic
        
        
        
        let disPlayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") ?? "defaultlog"

        
        let emailServer = SKPSMTPMessage()
        emailServer.delegate = self
        emailServer.fromEmail = "1017hudan@163.com" //发件人邮箱
        emailServer.toEmail = "1017hudan@163.com" //收件人邮箱"
        emailServer.login = "1017hudan@163.com" //发件人邮箱账号
        emailServer.pass = "GAUZskr36WwzwEBQ" //密码或者授权码
     
     /* Notice: 填好SMTP的服务器，第二步已经记录好了 */
         emailServer.relayHost = "smtp.163.com"
         emailServer.requiresAuth = true
          emailServer.wantsSecure = true//是否用ssl
        
        
        
      
        let infoDictionary = Bundle.main.infoDictionary!
         let majorVersion = infoDictionary["CFBundleShortVersionString"]//主程序版本号
        let minorVersion = infoDictionary["CFBundleVersion"]//版本号（内部标示）
        let appVersion = majorVersion as! String
         
        //设备信息
        let iosVersion = UIDevice.current.systemVersion //iOS版本
         let systemName = UIDevice.current.systemName //设备名称
     
         
        
             
         emailServer.subject = "user log track"
        let messageContent = "\(disPlayName)\n版本号：\(appVersion)(\(minorVersion.unwrap))\niOS版本：\(iosVersion)\n\(UIDevice.current.modelName)\n备注：\(remark)\n回访方式：\(contact)\n\(userDic)"
         let messagePart = [kSKPSMTPPartContentTypeKey: "text/plain",
                            kSKPSMTPPartMessageKey: messageContent]
        
        let logP = "/Caches/Logs/\(disPlayName).log"
        
        var imgPartArr = [[String:String?]]()
        for item in imgs {
             let data:Data = resetImgSize(sourceImage: item, maxImageLenght: 900, maxSizeKB: 300)
            let nsdata = data as NSData
             let imgPart = [kSKPSMTPPartContentTypeKey:"image/jpg;\r\n\tx-unix-mode=0644;\r\n\tname=\"image.jpg\"",
                     kSKPSMTPPartContentDispositionKey:"attachment;\r\n\tfilename=\"image.jpg\"",
                                kSKPSMTPPartMessageKey:nsdata.encodeBase64ForData(),
                kSKPSMTPPartContentTransferEncodingKey:"base64"]
            imgPartArr.append(imgPart)
        }
        
        
        
         
        
        
        if let documentPaths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first {
            let sssss = documentPaths.appending(logP)
             let txtData = NSData(contentsOfFile: sssss)
           if txtData.isSome {
               let txtPart = [kSKPSMTPPartContentTypeKey:"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"AAAA.txt\"",
                       kSKPSMTPPartContentDispositionKey:"attachment;\r\n\tfilename=\"details.txt\"",
                                  kSKPSMTPPartMessageKey:txtData!.encodeBase64ForData(),
                  kSKPSMTPPartContentTransferEncodingKey:"base64"]
               emailServer.parts = [messagePart,txtPart] + imgPartArr
               
               KSLog("附件成功")
           } else {
               KSLog("附件无")
               emailServer.parts = [messagePart] + imgPartArr
           }
        } else {
            KSLog("附件无")
            emailServer.parts = [messagePart] + imgPartArr
        }
       
  
      
         emailServer.send()
     }

 //MARK:SKPSMTPMessageDelegate
     func messageSent(_ message: SKPSMTPMessage!) {
         KSToast("日志上报成功")
         if let clo = self.refreshClosure {
             clo()
         }
     }
     
     //MARK:SKPSMTPMessageDelegate
     func messageFailed(_ message: SKPSMTPMessage!, error: Error!) {
         KSLog("日志上报出现错误，\(error.localizedDescription)")
     }
     
   
}

 
 
